<?php

/**
 * @file
 * LiveChatSupportSystem class definition.
 */

/**
 * Represents a LiveChatSupportSystem.
 */
class ChatroomLivesupport extends Chatroom {

  protected $status = 0;

  protected $modified = 0;

  public function __construct($cid = FALSE) {
    if ($cid) {
      $this->load($cid);
    }
  }

  public function load($cid) {
    $data = db_query('SELECT * FROM {chatroom} WHERE cid = :cid', array(':cid' => $cid))->fetchObject();
    if ($data) {
      $this->cid = $data->cid;
      $this->uid = $data->uid;
      $this->public = $data->public;
      $this->archived = $data->archived;
      $this->title = $data->title;
      $this->format = $data->format;
      $this->status = $data->status;
      $this->modified = $data->modified;
      $this->loadAllowedRoles();
      $this->loadAllowedUids();
      $this->loadLatestMessage();
    }
  }

  protected function loadAllowedUids() {
    $this->allowedUids = array();
    $uids = db_query('SELECT uid, read_only, modified FROM {chatroom_user} WHERE cid = :cid ORDER BY modified ASC', array(':cid' => $this->cid))->fetchAll();
    foreach ($uids as $uid) {
      $this->allowedUids[] = $uid;
    }
    return $this->allowedUids;
  }
  /**
   * Update the uids allowed to access a chat.
   *
   * @param mixed $uids
   * @return void
   */
  protected function updateUids() {
    foreach ($this->allowedUids as $uid) {
      $count = db_select('chatroom_user', 'u')
        ->fields('u')
        ->condition('uid', $uid->uid)
        ->condition('cid', $this->cid)
        ->execute()->rowCount();
      $data = array('uid' => $uid->uid, 'cid' => $this->get('cid'), 'read_only' => $uid->read_only, 'modified' => $uid->modified);
      if (!$count) {
        drupal_write_record('chatroom_user', $data);
      }
      else {
        drupal_write_record('chatroom_user', $data, array('uid', 'cid'));
      }
    }
  }

  /**
   * Get the latest user joined chat
   */
  public function getLatestUid() {
    $user = db_query('SELECT * FROM {chatroom_user} WHERE cid = :cid ORDER BY modified DESC LINIT 1', array(':cid' => $this->cid))->fetchAll();
    if ($user) {
      return $user->uid;
    }
  }

  /**
   * Get the message count for a chat.
   */
  public function getMessageCount() {
    $sql = 'SELECT COUNT(cmid) FROM {chatroom_msg} WHERE cid = :cid';
    return db_query($sql, array(':cid' => $this->get('cid')))->fetchField();
  }

  public function save() {
    $transaction = db_transaction();
    try {
      $data = array(
        'title' => $this->title,
        'public' => $this->public,
        'uid' => $this->uid,
        'archived' => $this->archived,
        'format' => $this->format,
        'status' => $this->status,
        'modified' => $this->modified
      );
      $op = $this->cid ? 'update' : 'insert';
      if ($op == 'update') {
        $data['cid'] = $this->cid;
        drupal_write_record('chatroom', $data, 'cid');
      }
      else {
        drupal_write_record('chatroom', $data);
        $this->cid = $data['cid'];
      }
      if ($this->hasChanged('allowedUids')) {
        $this->updateUids();
      }
      module_invoke_all('chatroom_' . $op, $this);
      return TRUE;
    }
    catch (Exception $e) {
      $transaction->rollback();
      watchdog_exception('chatroom_save', $e);
      return FALSE;
    }
  }

  /**
   * Why? Because fields caching is not what we want.
   */
  public function __wakeup() {
    $this->load($this->cid);
  }
}

